import 'package:flutter/material.dart';

//父Widget
class CurrentStatePage extends StatefulWidget {
  const CurrentStatePage({super.key});

  @override
  State<CurrentStatePage> createState() => _CurrentStatePageState();
}

class _CurrentStatePageState extends State<CurrentStatePage> {
  final GlobalKey _globalKey1 = GlobalKey();

  @override
  Widget build(BuildContext context) {
    // print(MediaQuery.of(context).orientation);
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //1. 获取子组件currentState 属性 和  方法  --- __BoxStateState
          var BoxState = _globalKey1.currentState as __BoxStateState;
          print(BoxState._count);
          setState(() {
            BoxState._count++;
          });
          //获取子元素的方法
          BoxState.run();

          //2. 获取子 Widget  ----  StatefulWidget
          var BoxWidget = _globalKey1.currentWidget as _BoxState;
          print(BoxWidget.color);
          // setState(() {
          //   BoxWidget.color = Colors.yellow;
          // });  不可以改变

          //3. 获取子组件渲染的属性
          var renderBox =
              _globalKey1.currentContext!.findRenderObject() as RenderBox;
          print(renderBox.size); //Size(100.0, 100.0)
        },
        child: Icon(Icons.add),
      ),
      appBar: AppBar(title: Text('GlobalKey 获取子组件')),
      body: Center(child: _BoxState(key: _globalKey1)),
    );
  }
}

// 子Widget
class _BoxState extends StatefulWidget {
  final double width;
  final double height;
  final Color color;
  const _BoxState({
    super.key,
    this.width = 100,
    this.height = 100,
    this.color = Colors.red,
  });

  @override
  State<_BoxState> createState() => __BoxStateState();
}

class __BoxStateState extends State<_BoxState> {
  int _count = 0;
  void run() {
    print('我是子组件的run方法');
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: widget.width,
      height: widget.height,
      // color: widget.color,
      child: ElevatedButton(
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: widget.color,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        ),
        child: Text(
          '$_count',
          style: Theme.of(context).textTheme.headlineMedium,
        ),
      ),
    );
  }
}
